package com.ruoyi.market.service.oss;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.TagSet;
import com.ruoyi.common.service.IUploadFileService;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.market.OssDirEnum;
import com.ruoyi.market.config.OssConfig;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class IAliYunOssService implements  IUploadFileService {

    @Autowired
    OssConfig ossConfig;

    @Override
    public String uploadFile(MultipartFile file, String fileType) throws IOException {

        OssDirEnum ossDirEnum = OssDirEnum.getPathByValue(fileType);
        if (ObjectUtils.isEmpty(ossDirEnum)){
            return "";
        }

        String uuidStr = UUID.fastUUID().toString();
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.indexOf("."));
        String objectKey = StrUtil.format(ossDirEnum.getPrefix(), uuidStr + suffix);
        objectKey = StrUtil.format(ossDirEnum.getPath(), objectKey);

        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKey(), ossConfig.getAccessSecret());
        PutObjectResult putObjectResult = ossClient.putObject(ossConfig.getBucketName(), objectKey, file.getInputStream());

        String fileUrl = ossConfig.getHostUrl() + objectKey;

        return fileUrl;

    }

    @Override
    public void getObjectTag() {
        OSS ossClient = null;
        try {

            String objectName = "apk/rxh.apk";

            // 获取文件的标签。
            ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKey(), ossConfig.getAccessSecret());
            TagSet tagSet = ossClient.getObjectTagging(ossConfig.getBucketName(), objectName);
            Map<String, String> tags = tagSet.getAllTags();

            // 查看标签信息。
            System.out.println("object tagging: "+ tags.toString());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

}
